<template>
  <div class="history-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>
            <el-icon><Clock /></el-icon>
            转换历史记录
          </h3>
          <el-button type="primary" @click="refreshHistory" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="conversions"
        style="width: 100%"
        empty-text="暂无转换记录"
      >
        <el-table-column prop="originalFileName" label="文件名" min-width="200">
          <template #default="{ row }">
            <el-icon><Document /></el-icon>
            {{ row.originalFileName }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              :icon="getStatusIcon(row.status)"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="fileSize" label="文件大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="completedAt" label="完成时间" width="180">
          <template #default="{ row }">
            {{ row.completedAt ? formatDate(row.completedAt) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'COMPLETED'"
              type="primary"
              size="small"
              @click="downloadPpt(row)"
            >
              <el-icon><Download /></el-icon>
              下载
            </el-button>
            <el-button
              v-if="row.status === 'FAILED'"
              type="info"
              size="small"
              @click="showError(row)"
            >
              <el-icon><InfoFilled /></el-icon>
              详情
            </el-button>
            <el-button
              v-if="row.status === 'PENDING' || row.status === 'PROCESSING'"
              type="warning"
              size="small"
              @click="checkStatus(row)"
            >
              <el-icon><Refresh /></el-icon>
              检查
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 错误详情对话框 -->
    <el-dialog
      v-model="errorDialogVisible"
      title="转换失败详情"
      width="500px"
    >
      <div class="error-content">
        <p><strong>错误信息：</strong></p>
        <el-alert
          :title="currentError"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { convertApi } from '../api/auth'

export default {
  name: 'History',
  setup() {
    const loading = ref(false)
    const conversions = ref([])
    const errorDialogVisible = ref(false)
    const currentError = ref('')

    const loadHistory = async () => {
      try {
        loading.value = true
        const response = await convertApi.history()
        if (response.data.success) {
          conversions.value = response.data.data
        }
      } catch (error) {
        ElMessage.error('加载历史记录失败')
      } finally {
        loading.value = false
      }
    }

    const refreshHistory = () => {
      loadHistory()
    }

    const getStatusType = (status) => {
      switch (status) {
        case 'COMPLETED': return 'success'
        case 'FAILED': return 'danger'
        case 'PROCESSING': return 'warning'
        case 'PENDING': return 'info'
        default: return 'info'
      }
    }

    const getStatusIcon = (status) => {
      switch (status) {
        case 'COMPLETED': return 'Check'
        case 'FAILED': return 'Close'
        case 'PROCESSING': return 'Loading'
        case 'PENDING': return 'Clock'
        default: return 'InfoFilled'
      }
    }

    const getStatusText = (status) => {
      switch (status) {
        case 'COMPLETED': return '已完成'
        case 'FAILED': return '失败'
        case 'PROCESSING': return '处理中'
        case 'PENDING': return '等待中'
        default: return '未知'
      }
    }

    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const formatDate = (dateString) => {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    const downloadPpt = async (conversion) => {
      try {
        const response = await convertApi.download(conversion.id)
        
        const blob = new Blob([response.data], { 
          type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' 
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = conversion.originalFileName.replace('.pdf', '.pptx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('PPT文件下载成功')
      } catch (error) {
        ElMessage.error('下载失败: ' + (error.message || '未知错误'))
      }
    }

    const showError = (conversion) => {
      currentError.value = conversion.errorMessage || '未知错误'
      errorDialogVisible.value = true
    }

    const checkStatus = async (conversion) => {
      try {
        const response = await convertApi.status(conversion.id)
        if (response.data.success) {
          const updatedConversion = response.data.data
          const index = conversions.value.findIndex(c => c.id === conversion.id)
          if (index !== -1) {
            conversions.value[index] = updatedConversion
          }
          ElMessage.success('状态已更新')
        }
      } catch (error) {
        ElMessage.error('检查状态失败')
      }
    }

    onMounted(() => {
      loadHistory()
    })

    return {
      loading,
      conversions,
      errorDialogVisible,
      currentError,
      refreshHistory,
      getStatusType,
      getStatusIcon,
      getStatusText,
      formatFileSize,
      formatDate,
      downloadPpt,
      showError,
      checkStatus
    }
  }
}
</script>

<style scoped>
.history-container {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #409EFF;
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-content {
  padding: 10px 0;
}

.error-content p {
  margin-bottom: 10px;
  color: #606266;
}
</style> 